package pl.edu.wat.erp.client.administration;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import wat.ziszcommon.clientgui.MyJPanel;
import wat.ziszcommon.clientgui.MyJTree;
import wat.ziszcommon.invoker.UnauthorizedAccesException;
import wat.ziszcommon.invoker.MethodException;

/**
 *
 * @author P.B. & L.G. & K.K.
 */
public class UserAdministrationClient extends MyJPanel {

    private DefaultComboBoxModel defaultComboBoxModel;
    private DefaultListModel myRoles;
    private DefaultListModel avRoles;
    private DefaultListModel rights;
    private Map<String, Set<String>> users;
    private Map<String, Map<String, String>> roles;

    public UserAdministrationClient(String nazwa, MyJTree tree) {
        super(nazwa, tree);
        initComponents();
    // tutaj nic nie robimy - zapraszam do initClient() ;)

    }

   // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
   private void initComponents() {

      jLabel1 = new javax.swing.JLabel();
      jScrollPane2 = new javax.swing.JScrollPane();
      myRolesList = new javax.swing.JList();
      jLabel2 = new javax.swing.JLabel();
      jLabel3 = new javax.swing.JLabel();
      jScrollPane3 = new javax.swing.JScrollPane();
      avRolesList = new javax.swing.JList();
      addRole = new javax.swing.JButton();
      removeRole = new javax.swing.JButton();
      userList = new javax.swing.JComboBox();
      removeUserButton = new javax.swing.JButton();
      addUserButton = new javax.swing.JButton();
      addRoleButton = new javax.swing.JButton();
      removeRoleButton = new javax.swing.JButton();
      jScrollPane1 = new javax.swing.JScrollPane();
      rightsList = new javax.swing.JList();
      jLabel4 = new javax.swing.JLabel();
      addRightButton = new javax.swing.JButton();
      removeRightButton = new javax.swing.JButton();

      setName("Form"); // NOI18N

      org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(UserAdministrationClient.class);
      jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
      jLabel1.setName("jLabel1"); // NOI18N

      jScrollPane2.setName("jScrollPane2"); // NOI18N

      myRolesList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
      myRolesList.setName("myRolesList"); // NOI18N
      myRolesList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
         public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
            myRolesListValueChanged(evt);
         }
      });
      jScrollPane2.setViewportView(myRolesList);

      jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
      jLabel2.setName("jLabel2"); // NOI18N

      jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
      jLabel3.setName("jLabel3"); // NOI18N

      jScrollPane3.setName("jScrollPane3"); // NOI18N

      avRolesList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
      avRolesList.setName("avRolesList"); // NOI18N
      avRolesList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
         public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
            avRolesListValueChanged(evt);
         }
      });
      jScrollPane3.setViewportView(avRolesList);

      addRole.setText(resourceMap.getString("addRole.text")); // NOI18N
      addRole.setEnabled(false);
      addRole.setName("addRole"); // NOI18N
      addRole.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            addRoleActionPerformed(evt);
         }
      });

      removeRole.setText(resourceMap.getString("removeRole.text")); // NOI18N
      removeRole.setEnabled(false);
      removeRole.setName("removeRole"); // NOI18N
      removeRole.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            removeRoleActionPerformed(evt);
         }
      });

      userList.setName("userList"); // NOI18N
      userList.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            userListActionPerformed(evt);
         }
      });

      removeUserButton.setText(resourceMap.getString("removeUserButton.text")); // NOI18N
      removeUserButton.setName("removeUserButton"); // NOI18N
      removeUserButton.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            removeUserButtonActionPerformed(evt);
         }
      });

      addUserButton.setText(resourceMap.getString("addUserButton.text")); // NOI18N
      addUserButton.setName("addUserButton"); // NOI18N
      addUserButton.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            addUserButtonActionPerformed(evt);
         }
      });

      addRoleButton.setText(resourceMap.getString("addRoleButton.text")); // NOI18N
      addRoleButton.setName("addRoleButton"); // NOI18N
      addRoleButton.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            addRoleButtonActionPerformed(evt);
         }
      });

      removeRoleButton.setText(resourceMap.getString("removeRoleButton.text")); // NOI18N
      removeRoleButton.setName("removeRoleButton"); // NOI18N
      removeRoleButton.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            removeRoleButtonActionPerformed(evt);
         }
      });

      jScrollPane1.setName("jScrollPane1"); // NOI18N

      rightsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
      rightsList.setName("rightsList"); // NOI18N
      jScrollPane1.setViewportView(rightsList);

      jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
      jLabel4.setName("jLabel4"); // NOI18N

      addRightButton.setText(resourceMap.getString("addRightButton.text")); // NOI18N
      addRightButton.setName("addRightButton"); // NOI18N
      addRightButton.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            addRightButtonActionPerformed(evt);
         }
      });

      removeRightButton.setText(resourceMap.getString("removeRightButton.text")); // NOI18N
      removeRightButton.setName("removeRightButton"); // NOI18N
      removeRightButton.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            removeRightButtonActionPerformed(evt);
         }
      });

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
      this.setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addGroup(layout.createSequentialGroup()
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(jLabel2)
                     .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                     .addComponent(addRole, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                     .addComponent(removeRole))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                     .addComponent(jLabel3))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(jLabel4)
                     .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)))
               .addGroup(layout.createSequentialGroup()
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(userList, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                     .addComponent(jLabel1))
                  .addGap(6, 6, 6)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                     .addComponent(addUserButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                     .addComponent(removeUserButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                     .addGroup(layout.createSequentialGroup()
                        .addComponent(removeRoleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeRightButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                     .addGroup(layout.createSequentialGroup()
                        .addComponent(addRoleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addRightButton)))))
            .addContainerGap(25, Short.MAX_VALUE))
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                  .addComponent(addUserButton)
                  .addComponent(addRoleButton)
                  .addComponent(addRightButton))
               .addComponent(jLabel1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(userList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(removeUserButton)
               .addComponent(removeRoleButton)
               .addComponent(removeRightButton))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(jLabel2)
               .addComponent(jLabel3)
               .addComponent(jLabel4))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
               .addComponent(jScrollPane1)
               .addComponent(jScrollPane3)
               .addGroup(layout.createSequentialGroup()
                  .addGap(53, 53, 53)
                  .addComponent(addRole)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addComponent(removeRole))
               .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
            .addContainerGap(65, Short.MAX_VALUE))
      );
   }// </editor-fold>//GEN-END:initComponents

    private void addRoleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRoleActionPerformed
        String activeUser = (String) userList.getSelectedItem();
        users.get(activeUser).add((String) avRolesList.getSelectedValue());
        try {
            setUsers(users);
            setRoles(roles);
            initClient();
        } catch (MethodException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
        } catch (UnauthorizedAccesException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
        }

}//GEN-LAST:event_addRoleActionPerformed

    private void userListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userListActionPerformed

        myRoles.clear();
        avRoles.clear();

        String activeUserName = (String) userList.getSelectedItem();
        Set<String> rolesMy = users.get(activeUserName);
        Set<String> rolesAll = roles.keySet();
        for (String string : rolesMy) {
            if (rolesAll.contains(string)) {
                myRoles.addElement(string);
            }
        }
        for (String string : rolesAll) {
            if (!rolesMy.contains(string)) {
                avRoles.addElement(string);
            }
        }
    }//GEN-LAST:event_userListActionPerformed

    private void myRolesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_myRolesListValueChanged

        if (myRolesList.getSelectedIndex() != -1) {

            rights.clear();
            addRole.setEnabled(false);
            removeRole.setEnabled(true);

            String activeRole = (String) myRolesList.getSelectedValue();
            avRolesList.clearSelection();
            Map<String, String> activeRights = roles.get(activeRole);
            if (activeRights != null) {
                Set<String> keys = activeRights.keySet();
                for (String string : keys) {
                    rights.addElement(string + " -> " + activeRights.get(string));
                }
            }
        }
    }//GEN-LAST:event_myRolesListValueChanged

    private void avRolesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_avRolesListValueChanged

        if (avRolesList.getSelectedIndex() != -1) {

            rights.clear();
            addRole.setEnabled(true);
            removeRole.setEnabled(false);

            String activeRole = (String) avRolesList.getSelectedValue();
            myRolesList.clearSelection();
            Map<String, String> activeRights = roles.get(activeRole);
            if (activeRights != null) {
                Set<String> keys = activeRights.keySet();
                for (String string : keys) {
                    rights.addElement(string + " -> " + activeRights.get(string));
                }
            }
        }
    }//GEN-LAST:event_avRolesListValueChanged

    private void removeRoleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRoleActionPerformed
        String activeUser = (String) userList.getSelectedItem();
        users.get(activeUser).remove((String) myRolesList.getSelectedValue());
        try {
            setUsers(users);
            setRoles(roles);
            initClient();
        } catch (MethodException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
        } catch (UnauthorizedAccesException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_removeRoleActionPerformed

    private void addUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addUserButtonActionPerformed
        JFrame question = new JFrame("Dodawanie użytkownika");
        question.setSize(300, 100);
        JPanel panel = new JPanel(new BorderLayout());
        JPanel panelQ = new JPanel(new BorderLayout());
        JPanel panelL = new JPanel(new BorderLayout());

        final JTextField nameQ = new JTextField();
        final JTextField passQ = new JPasswordField();
        final JTextField fullNameQ = new JTextField();
        JLabel nameL = new JLabel("Login");
        JLabel passL = new JLabel("Hasło");
        JLabel fullNameL = new JLabel("Pełna nazwa");
        JButton ok = new JButton("OK");
        ok.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (nameQ.getText().equals("") == false && fullNameQ.getText().equals("") == false && passQ.getText().equals("") == false) {
                    try {
                        addUser(nameQ.getText(), fullNameQ.getText(), passQ.getText());
                        initClient();
                    } catch (MethodException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
                    } catch (UnauthorizedAccesException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Proszę wypełnić wszystkie pola", "Informacja", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        question.add(panel);
        panel.add(panelL, BorderLayout.WEST);
        panel.add(panelQ, BorderLayout.CENTER);
        panel.add(ok, BorderLayout.EAST);

        panelQ.add(nameQ, BorderLayout.NORTH);
        panelQ.add(passQ, BorderLayout.CENTER);
        panelQ.add(fullNameQ, BorderLayout.SOUTH);

        panelL.add(nameL, BorderLayout.NORTH);
        panelL.add(passL, BorderLayout.CENTER);
        panelL.add(fullNameL, BorderLayout.SOUTH);
        question.setVisible(true);

    }//GEN-LAST:event_addUserButtonActionPerformed

    private void removeUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeUserButtonActionPerformed
        String activeUser = (String) userList.getSelectedItem();
        int answer = JOptionPane.showConfirmDialog(this, "Czy na pewno usunąć użytkownika " + activeUser, "Pytanie", JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            try {
                removeUser(activeUser);
                initClient();
            } catch (MethodException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
            } catch (UnauthorizedAccesException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_removeUserButtonActionPerformed

    private void addRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRoleButtonActionPerformed
        String roleName = JOptionPane.showInputDialog("Podaj nazwę roli");
        try {
            addRole(roleName);
            initClient();
        } catch (MethodException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
        } catch (UnauthorizedAccesException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_addRoleButtonActionPerformed

    private void removeRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRoleButtonActionPerformed
        String activeRole = "";
        if (myRolesList.getSelectedIndex() != -1) {
            activeRole = (String) myRolesList.getSelectedValue();
        } else if (avRolesList.getSelectedIndex() != -1) {
            activeRole = (String) avRolesList.getSelectedValue();
        } else {
            JOptionPane.showMessageDialog(this, "Proszę wybrać rolę", "Informacja", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int answer = JOptionPane.showConfirmDialog(this, "Czy na pewno usunąć rolę " + activeRole, "Pytanie", JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            System.out.println("usuwam role...");
            try {
                removeRole(activeRole);
                initClient();
            } catch (MethodException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
            } catch (UnauthorizedAccesException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_removeRoleButtonActionPerformed

    private void addRightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRightButtonActionPerformed
        String activeRole = "";
        if (myRolesList.getSelectedIndex() != -1) {
            activeRole = (String) myRolesList.getSelectedValue();
        } else if (avRolesList.getSelectedIndex() != -1) {
            activeRole = (String) avRolesList.getSelectedValue();
        } else {
            JOptionPane.showMessageDialog(this, "Proszę wybrać rolę", "Informacja", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        final Map<String, String> rightsM = roles.get(activeRole);

        JFrame question = new JFrame("Dodawanie uprawnień");
        question.setSize(300, 100);
        JPanel panel = new JPanel(new BorderLayout());
        JPanel panelQ = new JPanel(new BorderLayout());
        JPanel panelL = new JPanel(new BorderLayout());

        final JTextField nameQ = new JTextField();
        final JTextField dirQ = new JTextField();
        JLabel nameL = new JLabel("Nazwa modułu");
        JLabel passL = new JLabel("Ścieżka");
        JButton ok = new JButton("OK");
        ok.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (nameQ.getText().equals("") == false && dirQ.getText().equals("") == false) {
                    try {
                        rightsM.put(nameQ.getText(), dirQ.getText());
                        setRoles(roles);
                        initClient();
                    } catch (MethodException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
                    } catch (UnauthorizedAccesException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Proszę wypełnić wszystkie pola", "Informacja", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        question.add(panel);
        panel.add(panelL, BorderLayout.WEST);
        panel.add(panelQ, BorderLayout.CENTER);
        panel.add(ok, BorderLayout.EAST);

        panelQ.add(nameQ, BorderLayout.NORTH);
        panelQ.add(dirQ, BorderLayout.CENTER);

        panelL.add(nameL, BorderLayout.NORTH);
        panelL.add(passL, BorderLayout.CENTER);
        question.setVisible(true);

    }//GEN-LAST:event_addRightButtonActionPerformed

    private void removeRightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRightButtonActionPerformed
        try {
            String activeRole = "";
            if (myRolesList.getSelectedIndex() != -1) {
                activeRole = (String) myRolesList.getSelectedValue();
            } else if (avRolesList.getSelectedIndex() != -1) {
                activeRole = (String) avRolesList.getSelectedValue();
            } else {
                JOptionPane.showMessageDialog(this, "Proszę wybrać rolę", "Informacja", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String activeRight = "";
            if (rightsList.getSelectedIndex() != -1) {
                activeRight = (String) rightsList.getSelectedValue();
            } else {
                JOptionPane.showMessageDialog(this, "Proszę wybrać uprawnienie", "Informacja", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            Map<String, String> rightsM = roles.get(activeRole);
            int endI = activeRight.indexOf(" -> ");
            activeRight = activeRight.substring(0, endI);
            rightsM.remove(activeRight);
            setRoles(roles);
            initClient();
        } catch (MethodException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
        } catch (UnauthorizedAccesException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
        }



    }//GEN-LAST:event_removeRightButtonActionPerformed

   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JButton addRightButton;
   private javax.swing.JButton addRole;
   private javax.swing.JButton addRoleButton;
   private javax.swing.JButton addUserButton;
   private javax.swing.JList avRolesList;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JLabel jLabel2;
   private javax.swing.JLabel jLabel3;
   private javax.swing.JLabel jLabel4;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JScrollPane jScrollPane2;
   private javax.swing.JScrollPane jScrollPane3;
   private javax.swing.JList myRolesList;
   private javax.swing.JButton removeRightButton;
   private javax.swing.JButton removeRole;
   private javax.swing.JButton removeRoleButton;
   private javax.swing.JButton removeUserButton;
   private javax.swing.JList rightsList;
   private javax.swing.JComboBox userList;
   // End of variables declaration//GEN-END:variables

    @Override
    public void initClient() {
        System.out.println("Inicjalizacja modulu administracji uzytkownikami...");
        defaultComboBoxModel =
                new DefaultComboBoxModel();
        myRoles =
                new DefaultListModel();
        avRoles =
                new DefaultListModel();
        rights =
                new DefaultListModel();
        userList.setModel(defaultComboBoxModel);
        myRolesList.setModel(myRoles);
        avRolesList.setModel(avRoles);
        rightsList.setModel(rights);

        try {
            users = getUsers();
            roles =
                    getRoles();
        } catch (MethodException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd", JOptionPane.ERROR_MESSAGE);
        } catch (UnauthorizedAccesException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Błąd autoryzacji", JOptionPane.ERROR_MESSAGE);
        }

        Set<String> usersNames = users.keySet();

        for (String string : usersNames) {
            defaultComboBoxModel.addElement(string);
        }

    }

    private Map<String, Set<String>> getUsers() throws UnauthorizedAccesException, MethodException {
        // username:role,role,role;username:role,role
        String usersList = invokeMethod("getUsersList", "");

        HashMap<String, Set<String>> users = new HashMap<String, Set<String>>();

        for (String userAndRoles : usersList.split(";")) {
            String[] user = userAndRoles.split(":");
            String userName = user[0];
            HashSet<String> rolesSet = new HashSet<String>();
            if (user.length == 2) { //posiada role
                String[] roles = user[1].split(",");
                for (String role : roles) {
                    rolesSet.add(role);
                }

            }
            users.put(userName, rolesSet);
        }

        return users;
    }

    private void setUsers(Map<String, Set<String>> users) throws UnauthorizedAccesException, MethodException {
        // username:role,role,role;username:role,role

        String response = "";
        Set<String> keys = users.keySet();
        for (String username : keys) {
            System.out.println("USER:" + username);
            response =
                    response + username + ":";
            Set<String> roles = users.get(username);
            for (String role : roles) {
                System.out.println("ROLE:" + role);
                response =
                        response + role + ",";
            }

            if (response.lastIndexOf(",") == response.length() - 1) {
                response = response.substring(0, response.length() - 1);
            }

            response = response + ";";

        }

        if (response.lastIndexOf(";") == response.length() - 1) {
            response = response.substring(0, response.length() - 1);
        }

        invokeMethod("setUsersList", response);
    }

    private Map<String, Map<String, String>> getRoles() throws UnauthorizedAccesException, MethodException {
        // role:rightName-rightPath,rightName-rightPath;role:rightName-rightPath
        String rolesList = invokeMethod("getRolesList", "");

        HashMap<String, Map<String, String>> roles = new HashMap<String, Map<String, String>>();

        for (String rolesAndRights : rolesList.split(";")) {
            String[] role = rolesAndRights.split(":");
            String roleName = role[0];
            HashMap<String, String> rightsMap = new HashMap<String, String>();
            if (role.length == 2) { //posiada uprawnienia
                String[] rights = role[1].split(",");
                for (String right : rights) {
                    String[] s = right.split("-");
                    rightsMap.put(s[0], s[1]);
                }

            }
            roles.put(roleName, rightsMap);
        }

        return roles;
    }

    private void setRoles(Map<String, Map<String, String>> roles) throws UnauthorizedAccesException, MethodException {
        // role:rightName-rightPath,rightName-rightPath;role:rightName-rightPath

        String response = "";
        Set<String> keys = roles.keySet();
        for (String rolename : keys) {
            System.out.println("ROLE:" + rolename);
            response =
                    response + rolename + ":";
            Map<String, String> rightS = roles.get(rolename);
            Set<String> rightSkeys = rightS.keySet();
            for (String right : rightSkeys) {
                System.out.println("RIGHT:" + right);
                response =
                        response + right + "-" + rightS.get(right) + ",";
            }

            if (response.lastIndexOf(",") == response.length() - 1) {
                response = response.substring(0, response.length() - 1);
            }

            response = response + ";";

        }

        if (response.lastIndexOf(";") == response.length() - 1) {
            response = response.substring(0, response.length() - 1);
        }

        invokeMethod("setRolesList", response);
    }

    private void addUser(String userName, String fullUserName, String password) throws UnauthorizedAccesException, MethodException {
        invokeMethod("addUser", userName + ";" + fullUserName + ";" + password);
    }

    private void removeUser(String userName) throws UnauthorizedAccesException, MethodException {
        invokeMethod("removeUser", userName);
    }

    private void addRole(String roleName) throws UnauthorizedAccesException, MethodException {
        invokeMethod("addRole", roleName);
    }

    private void removeRole(String roleName) throws UnauthorizedAccesException, MethodException {
        invokeMethod("removeRole", roleName);
    }
}
